<?php

namespace frontend\controllers;

use backend\components\route\Helper;
use common\helpers\DataHelper;
use common\helpers\Tool;
use common\models\c2\entity\AppVersion;
use common\models\c2\entity\Children;
use common\models\c2\entity\Collection;
use common\models\c2\entity\Community;
use common\models\c2\entity\Config;
use common\models\c2\entity\Device;
use common\models\c2\entity\EntityAttachment;
use common\models\c2\entity\Family;
use common\models\c2\entity\FeeOrder;
use common\models\c2\entity\FeUser;
use common\models\c2\entity\LifeBill;
use common\models\c2\entity\Material;
use common\models\c2\entity\Order;
use common\models\c2\entity\Plan;
use common\models\c2\entity\Post;
use common\models\c2\entity\UserDevice;
use common\models\c2\entity\UserVip;
use common\models\c2\entity\Venue;
use common\models\c2\entity\Vip;
use common\models\c2\entity\Wish;
use common\models\c2\statics\CollectionStatus;
use common\models\c2\statics\ConfigType;
use common\models\c2\statics\EntityDeleteStatus;
use common\models\c2\statics\LifeBillStatus;
use common\models\c2\statics\LifeBillType;
use common\models\c2\statics\MaterialType;
use common\models\c2\statics\OrderStatus;
use common\models\c2\statics\PlanStatus;
use common\rest\models\c2\statics\ResponseDatum;
use cza\base\models\statics\EntityModelState;
use cza\base\models\statics\EntityModelStatus;
use dektrium\user\models\Account;
use Yii;
use yii\helpers\FileHelper;
use yii\helpers\Json;

/**
 * Site controller
 */
class V1Controller extends \common\rest\controllers\Controller
{

    public function actionWxConfig()
    {
        $url = \Yii::$app->request->post('url');

        $config = DataHelper::getWxConfig($url);
        if (!empty($config)) {
            return ResponseDatum::getSuccessDatum($config);
        }
    }

    public function actionMaterial()
    {
        $type = \Yii::$app->request->get('type');
        $model = Material::findOne(['type' => $type]);
        return ResponseDatum::getSuccessDatum($model);
    }

    public function actionCommunity()
    {
        $model = Community::getHashMap1('id2', 'name', ['status' => EntityModelState::STATUS_ENABLE]);
        if ($model) {
            return ResponseDatum::getSuccessDatum($model);
        }
        return ResponseDatum::getSuccessDatum([]);
    }

    public function actionSendCode()
    {
        $mobile_number = \Yii::$app->request->post('mobile_number');

        $result = FeUser::find()->select(['mobile_number'])->where(['mobile_number' => $mobile_number])->one();
        // if (!empty($result)) {
        //     return ResponseDatum::getErrorDatum([], ['msg' => '手机已被注册']);
        // }

        $code = Yii::$app->cache->get($mobile_number);
        if ($code) {
            return ResponseDatum::getSuccessDatum([], ['msg' => '验证码已发送']);
        }

        $code = rand(100000, 999999);

        $result = \Yii::$app->aliyun->sendSms('造就文化', 'SMS_230745055', $mobile_number, ['code' => $code,]);
        $result = json_decode($result, true);

        Yii::info($result);

        if ($result && $result['code'] == 200) {
            \Yii::$app->cache->set($mobile_number, $code, 900);
            return ResponseDatum::getSuccessDatum([], ['msg' => '验证码已发送，15分钟内有效']);
        }

        return ResponseDatum::getErrorDatum([], ['msg' => '验证码发送失败']);

    }

    public function actionSignin()
    {
        $account = \Yii::$app->request->post('account');
        $password = \Yii::$app->request->post('password');
        $model = FeUser::findOne(['mobile_number' => $account, 'status' => EntityModelStatus::STATUS_ACTIVE]);

        if ($model && $model->validatePassword($password)) {
            return ResponseDatum::getSuccessDatum($model);
        }
        return ResponseDatum::getErrorDatum();
    }

    public function actionSignup()
    {

        $community_id = \Yii::$app->request->post('community_id');
        $username = \Yii::$app->request->post('username');
        $address = \Yii::$app->request->post('address');
        $mobile_number = \Yii::$app->request->post('mobile_number');
        $code = \Yii::$app->request->post('code');
        $estate = \Yii::$app->request->post('estate');
        $idcard_back = \Yii::$app->request->post('idcard_back');
        $idcard_front = \Yii::$app->request->post('idcard_front');

        $cache_code = \Yii::$app->cache->get($mobile_number);
        if ($cache_code != $code) {
            return ResponseDatum::getErrorDatum([], ['msg' => '验证码错误']);
        }

        $user = FeUser::findOne(['mobile_number' => $mobile_number, 'status' => EntityModelStatus::STATUS_ACTIVE]);
        if ($user->status == EntityModelStatus::STATUS_ACTIVE && $mobile_number == $user->mobile_number) {
            return ResponseDatum::getErrorDatum([], ['msg' => '手机号已注册']);
        }

        $model = new FeUser();
        $model->community_id = $community_id;
        $model->username = $username;
        $model->address = $address;
        $model->mobile_number = $mobile_number;
        $model->status = EntityModelStatus::STATUS_INACTIVE;
        $path1 = Tool::saveBase64($estate);
        if ($path1) {
            $model->estate = $path1;
        }
        $path2 = Tool::saveBase64($idcard_back);
        if ($path2) {
            $model->idcard_back = $path2;
        }
        $path3 = Tool::saveBase64($idcard_front);
        if ($path3) {
            $model->idcard_front = $path3;
        }
        if ($model->save()) {
            \Yii::$app->cache->delete($mobile_number);
            return ResponseDatum::getSuccessDatum();
        } else {
            \Yii::info($model->errors);
        }


        // $logicFilePath = Tool::saveBase64($avatar['data']);

        return ResponseDatum::getErrorDatum();
    }

    public function actionBindSub()
    {
        $username = \Yii::$app->request->post('username');
        $mobile_number = \Yii::$app->request->post('mobile_number');
        $password = \Yii::$app->request->post('password');
        $code = \Yii::$app->request->post('code');
        $uid = \Yii::$app->request->post('uid');

        $cache_code = \Yii::$app->cache->get($mobile_number);
        if ($cache_code != $code) {
            return ResponseDatum::getErrorDatum([], ['msg' => '验证码错误']);
        }

        $user = FeUser::findOne(['mobile_number' => $mobile_number, 'status' => EntityModelStatus::STATUS_ACTIVE]);
        if ($user->status == EntityModelStatus::STATUS_ACTIVE && $mobile_number == $user->mobile_number) {
            return ResponseDatum::getErrorDatum([], ['msg' => '手机号已注册']);
        }

        $main_user = FeUser::findOne($uid);
        if (!$main_user) {
            return ResponseDatum::getErrorDatum();
        }

        $model = new FeUser();
        $model->muid = $main_user->id;
        $model->proprietor_id = $main_user->proprietor_id;
        $model->community_id = $main_user->community_id;
        $model->building_number_id = $main_user->building_number_id;
        $model->unit_id = $main_user->unit_id;
        $model->house_id = $main_user->house_id;
        $model->username = $username;
        $model->mobile_number = $mobile_number;
        $model->setPassword($password);
        if ($model->save()) {
            \Yii::$app->cache->delete($mobile_number);
            return ResponseDatum::getSuccessDatum($model);
        }
        return ResponseDatum::getErrorDatum();
    }

    public function actionSubUser()
    {
        $uid = \Yii::$app->request->get('uid');
        if (!empty($uid)) {
            $model = FeUser::find()->where(['muid' => $uid])->all();
            if (!empty($model)) {
                return ResponseDatum::getSuccessDatum($model);
            }
        }
        return ResponseDatum::getSuccessDatum([]);
    }
    public function actionUpdateAuth()
    {
        $id = \Yii::$app->request->post('id');
        $status = \Yii::$app->request->post('status');
        $model = FeUser::findOne($id);
        if (!empty($model)) {
            $model->updateAttributes(['status' => $status]);
            return ResponseDatum::getSuccessDatum();
        }
        return ResponseDatum::getSuccessDatum([]);
    }

    public function actionUserDevice()
    {
        $proprietor_id = \Yii::$app->request->get('proprietor_id');
        $models= UserDevice::find()->where(['proprietor_id' => $proprietor_id, 'is_deleted' => EntityDeleteStatus::STATUS_NOT_DELETED])->all();
        return ResponseDatum::getSuccessDatum($models);
    }

    public function actionDeviceUnlock()
    {
        $proprietor_id = \Yii::$app->request->post('proprietor_id');
        $device_id2 = \Yii::$app->request->post('device_id2');
        $uid = \Yii::$app->request->post('uid');

        $user = FeUser::findOne($uid);
        if ($user->status != EntityModelStatus::STATUS_ACTIVE) {
            return ResponseDatum::getErrorDatum(null, ['msg' => '暂无权限']);
        }

        $vip = UserVip::find()->where(['user_id' => $user->id])->one();
        // if (empty($vip) || $vip->active_day == 0) {
        //     return ResponseDatum::getErrorDatum(null, ['msg' => '暂无权限']);
        // }

        // $url = \Yii::$app->params['api_url'] . '/api/Building/SetRemoteUnlocking?supplier_id=' . \Yii::$app->params['supplier_id'];
        $url = \Yii::$app->params['api_url'] . '/api/Building/SetRemoteUnlocking?supplier_id=' . \Yii::$app->params['supplier_id'] . '&proprietor_id=' . $proprietor_id . '&device_id=' . $device_id2;
        // $data = [
        //     'proprietor_id' => $proprietor_id,
        //     'device_id' => $device_id2,
        // ];
        // $result = Tool::curlPost($url, json_encode($data));
        $result = Tool::curlGet($url);
        \Yii::info($result);

        $result = json_decode($result, true);
        if ($result['Status'] && $result['Status'] == 1) {
            return ResponseDatum::getSuccessDatum();
        }

        return ResponseDatum::getErrorDatum(null, ['msg' => $result['Message']]);
    }

    public function actionLifeBill()
    {
        $uid = \Yii::$app->request->get('uid');
        $year = date('Y');
        $models = LifeBill::find()->where(['user_id' => $uid, 'year' => $year])->all();
        if ($models) {
            return ResponseDatum::getSuccessDatum($models);
        }
        return ResponseDatum::getSuccessDatum([]);
    }

    public function actionVipCounpon()
    {
        $models = Vip::find()->where(['status' => EntityModelStatus::STATUS_ACTIVE])->orderBy(['position' => SORT_DESC])->all();
        if ($models) {
            return ResponseDatum::getSuccessDatum($models);
        }
        return ResponseDatum::getSuccessDatum([]);
    }


    public function actionLastVersion()
    {
        $ver = \Yii::$app->request->get('ver');
        $model = AppVersion::find()->where(['status' => EntityModelStatus::STATUS_ACTIVE])->orderBy(['version' => SORT_DESC])->one();
        if (!empty($model)) {
            return ResponseDatum::getSuccessDatum($model);
        }
        return ResponseDatum::getSuccessDatum(null);
    }

    public function actionDeviceInfo()
    {
        $device_id = \Yii::$app->request->get('id');
        $model = Device::findOne($device_id);

        if (!empty($model)) {
            $community_name = $model->community->name;
            $building_number_name = $model->buildingNumber->name;
            $unit_name = $model->unit->name;
            $device_name = $model->name;

            return ResponseDatum::getSuccessDatum(['info' => $community_name . ' / ' . $building_number_name . ' / ' . $unit_name . ' / ' . $device_name]);
        }
        return ResponseDatum::getErrorDatum();
    }

    public function actionUnpayBill() {
        $user_id = Yii::$app->request->get('uid');
        // $year = date('Y');
        // $month = date('M');
        // $model = LifeBill::find()->where(['user_id' => $user_id, 'year' => $year, 'month' => $month, 'status' => LifeBillStatus::STATUS_DEFAULT]);
        $models = LifeBill::find()->where(['user_id' => $user_id, 'status' => LifeBillStatus::STATUS_DEFAULT])->all();

        if (!empty($models)) {
            $data = '您好，您有';
            $text1 = '';
            foreach ($models as $model) {
                $text1 .= $model->month . '月' . LifeBillType::getLabel($model->type) . ' ';
            }
            $data .= $text1;
            $data .= '未缴费，请及时查看。';
            return ResponseDatum::getSuccessDatum($data);
        }

        return ResponseDatum::getSuccessDatum(null);
    }

}
